<template>
    <div class="select-cover">
        <img-cropper
            :height="configHeight"
            :width="configWidth"
            :limit-file-size="fileLimitSize"
            @on-error="handleError"
            @on-ok="handleOk"
        >
            <div v-if="props.data" class="img-add" :style="{ 'width': `${configWidth / 2}px`, 'height': `${configHeight / 2}px` }">
                <img :src="props.data" alt="" :style="{ 'width': `${configWidth / 2}px`, 'height': `${configHeight / 2}px` }" />
                <div class="add-cover">
                    <i class="iconfont icon-a-tianjiahuodongfengmian1x"></i>
                    <p>修改</p>
                </div>
            </div>
            <div class="img-up" v-else :style="{ 'width': `${configWidth / 2}px`, 'height': `${configHeight / 2}px` }">
                <div class="add-cover">
                    <i class="iconfont icon-a-tianjiahuodongfengmian1x"></i>
                    <p>{{ props.placeholder }}</p>
                </div>
            </div>
        </img-cropper>
    </div>
</template>

<script setup>
import { ref } from 'vue';

const emit = defineEmits(['update:data'])

const props = defineProps({
    data: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: '自定义封面'
    },
    configWidth: {
        type: [String, Number],
        default: 160
    },
    configHeight: {
        type: [String, Number],
        default: 90
    }
})


const fileLimitSize = ref(2 * 1024 * 1024);

/**
 * 返回错误信息，Error: { code, message }, 其中 1001 为文件类型错误，1002 为文件大小超出限制
 */
function handleError (msg) {
    let msgMap = { 1001: '文件类型不符合要求', 1002: '文件大小不符合要求' };
    G_dispatchEvent('toast', { message: msgMap[msg.code], type: 'error' });
}

/**
 * 返回裁剪后的图片地址
 */
function handleOk (result) {
    console.log(111, result);
    emit('update:data', result)
}

</script>

<style lang="scss" scoped>
.select-cover {
    img {
        position: relative;
        width: 160px;
        height: 90px;
        margin: 0 20px 20px 0;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
    }

   
}
.img-add {
    .add-cover {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        opacity: 0;
        transition: all 0.2s;
    }

    &:hover {
        width: 160px;
        height: 90px;
        background: rgba(0, 0, 0, 0.7);
        cursor: pointer;
        position: relative;
        img {
            opacity: 0.1;
        }
        .add-cover {
            opacity: 1;
        }
    }
}

.img-up {
    width: 160px;
    height: 90px;
    border-radius: 4px;
    border: 1px solid #cbe7ff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.add-cover {
    text-align: center;
    color: var(--srt-color-primary);
    cursor: pointer;

    .ivu-icon {
        font-size: 24px;
    }
}
</style>